package com.example.test_mqtt

import android.content.Context
import android.util.Log
import androidx.lifecycle.MutableLiveData
import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.*

class MQTTManager(
    private val context: Context,
    private val serverUri: String,
    private val clientId: String = "android_client_${System.currentTimeMillis()}"
) {
    private var mqttClient: MqttAndroidClient? = null
    private val TAG = "MQTTManager"
    val incomingMessage = MutableLiveData<MqttMessage>()

    // 连接配置
    private val mqttOptions = MqttConnectOptions().apply {
//        userName = "admin"       // 用户名（可选）
//        password = "password".toCharArray()  // 密码（可选）
        isCleanSession = true    // 是否清除会话
        connectionTimeout = 10   // 连接超时（秒）
        keepAliveInterval = 20   // 心跳间隔（秒）
        isAutomaticReconnect = true // 自动重连

        // 设置遗嘱消息（客户端异常断开时发送）
        setWill("status/$clientId", "offline".toByteArray(), 1, true)
    }

    // 初始化 MQTT 客户端
    fun connect() {
        mqttClient = MqttAndroidClient(context, serverUri, clientId).apply {
            setCallback(object : MqttCallback {
                override fun connectionLost(cause: Throwable?) {
                    Log.e(TAG, "连接断开: ${cause?.message}")
                    // 可在此处触发重连逻辑
                }

                override fun messageArrived(topic: String, message: MqttMessage) {
                    Log.d(TAG, "收到消息: [$topic] ${message.payload.toString(Charsets.UTF_8)}")
                    // 在此处理收到的消息（可通过 LiveData/EventBus 通知 UI）
                    incomingMessage.value = message
                }

                override fun deliveryComplete(token: IMqttDeliveryToken?) {
                    Log.d(TAG, "消息投递完成")
                }
            })
        }

        try {
            mqttClient?.connect(mqttOptions, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "MQTT 连接成功")
                    subscribe("test/topic") // 默认订阅主题
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.e(TAG, "MQTT 连接失败: ${exception?.message}")
                }
            })
        } catch (e: Exception) {
            Log.e(TAG, "连接异常: ${e.message}")
        }
    }

    // 订阅主题
    fun subscribe(topic: String, qos: Int = 1) {
        try {
            mqttClient?.subscribe(topic, qos, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "订阅成功: $topic")
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.e(TAG, "订阅失败: ${exception?.message}")
                }
            })
        } catch (e: Exception) {
            Log.e(TAG, "订阅异常: ${e.message}")
        }
    }

    // 发布消息
    fun publish(topic: String, message: String, qos: Int = 1, retained: Boolean = false) {
        try {
            val mqttMessage = MqttMessage(message.toByteArray(Charsets.UTF_8)).apply {
                this.qos = qos
                isRetained = retained
            }
            mqttClient?.publish(topic, mqttMessage)
            Log.d(TAG, "已发布消息到 [$topic]: $message")
        } catch (e: Exception) {
            Log.e(TAG, "发布失败: ${e.message}")
        }
    }

    // 断开连接
    fun disconnect() {
        try {
            mqttClient?.disconnect(null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    Log.d(TAG, "MQTT 已断开连接")
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    Log.e(TAG, "断开连接失败: ${exception?.message}")
                }
            })
        } catch (e: Exception) {
            Log.e(TAG, "断开连接异常: ${e.message}")
        }
    }
}